//
//  TestTableViewDataSource.m
//  sandbox
//
//  Created by 杨岑 on 5/6/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "TestTableViewDataSource.h"
#import "TestTableRowVC.h"
#import "TestTableCellView.h"
#import "TestTableTextView.h"


@implementation TestTableViewDataSource
{
    NSMutableArray* _items;
    NSInteger _count;
    NSMutableArray* _groupRows;
    NSMutableArray* _textViews;
    NSTableView* _tableview;
    NSMutableDictionary* _bag;
}

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _groupRows = [NSMutableArray array];
        _textViews = [NSMutableArray array];
        _bag = [NSMutableDictionary dictionary];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(frameDidChange:) name:NSViewFrameDidChangeNotification object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)frameDidChange:(NSNotification*)notification
{
    [self performSelectorOnMainThread:@selector(onFrameChange:) withObject:notification.object waitUntilDone:NO];
}

- (void)onFrameChange:(TestTableTextView*)textView
{
    //TestTableTextView* textView = notification.object;
    if ([_textViews indexOfObject:textView] != NSNotFound)
    {
        //NSLog(@"TableView textview frame change @%ld", textView.row);
        textView.heightConstraint.constant = textView.bounds.size.height;
        [_tableview noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndex:textView.row]];
    }
}

- (NSInteger)count
{
    return _count;
}

- (void)setCount:(NSInteger)count
{
    if (_count != count)
    {
        _count = count;
        _items = [NSMutableArray array];
        for (int i = 0; i < _count; i ++)
        {
            NSString* nameValue = [NSString stringWithFormat:@"row#%d", i];
        
            int n = rand() % 10 + 1;
            NSMutableString* valueValue = [NSMutableString string];
            for (int i = 0; i < n; i++)
            {
                [valueValue appendFormat:@"value#%d value\n", i];
            }
            
            NSMutableDictionary* item = [NSMutableDictionary dictionary];
            item[@"name"] = nameValue;
            item[@"value"] = valueValue;
            [_items addObject:item];
        }
    }
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    _tableview = tableView;
    return _items.count;
}

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    static NSTableCellView* prevCellView;
    
    if (row > 0 && row < _items.count)
    {
        NSString* cellValue = _items[row][tableColumn.identifier];
        NSTableCellView* cellView = [tableView makeViewWithIdentifier:tableColumn.identifier owner:tableView];
        cellView.textField.stringValue = cellValue;
        
        if (prevCellView)
        {
            prevCellView.nextKeyView = cellView;
        }
        
        if ([cellView isKindOfClass:[TestTableCellView class]])
        {
            TestTableCellView* testCellView = (TestTableCellView*)cellView;
            TestTableTextView* textView = (TestTableTextView*)testCellView.textView;
            textView.row = row;
            
            if ([_textViews indexOfObject:textView] == NSNotFound)
            {
                textView.editable = YES;
                textView.backgroundColor = [NSColor cyanColor];
                textView.translatesAutoresizingMaskIntoConstraints = NO;
                textView.postsFrameChangedNotifications = YES;
                [_textViews addObject:textView];
            }

            _bag[@(row)] = textView;
            textView.string = cellValue;
        }

        prevCellView = cellView;
        return cellView;
    }
    return nil;
}

- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
    if (row == 0)
    {
        TestTableRowVC* vc = [[TestTableRowVC alloc] initWithNibName:@"TestTableRow" bundle:nil];
        [_groupRows addObject:vc];
        [vc loadView];
        vc.view.translatesAutoresizingMaskIntoConstraints = NO;

        NSTableRowView* rv = [[NSTableRowView alloc] initWithFrame:NSMakeRect(0, 0, 100, 40)];
        [rv addSubview:vc.view];
        
        NSDictionary *viewsDictionary = @{@"v": vc.view};
        NSMutableArray* constraints = [NSMutableArray array];
        [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[v]-0-|" options:0 metrics:nil views:viewsDictionary]];
        
        [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[v]-0-|" options:0 metrics:nil views:viewsDictionary]];
        
        [rv addConstraints:constraints];
        return rv;
    }
    return nil;
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row
{
    if (row == 0) return 50;

    TestTableTextView* textView = _bag[@(row)];
    if (textView)
    {
        //NSLog(@"%08lx: %f", (NSInteger)textView, textView.bounds.size.height);
        return textView.heightConstraint.constant + 10;
    }
    return tableView.rowHeight + 5 * row;
}

@end
